#include "scope.h"

static void scope_proc_save_wave_data(char *value)
{
    lfs_file_t *file;
    int cur = (SCOPE_ADC_BUFFER_WORDS - dma_channel_hw_addr(g_scope_cfg.dma_chan_adc_data)->transfer_count) * 2;

    if (!value || strlen(value) == 0) {
        return;
    }
    pio_sm_set_enabled(SCOPE_ADC_PIO, SCOPE_ADC_TO_BUFFER_SM, false);
    file = lfs_spiflash_open(value, LFS_O_WRONLY | LFS_O_CREAT, false);
    if (file) {
        lfs_spiflash_write(file, &g_scope_cfg, sizeof(g_scope_cfg));
        if (SCOPE_ADC_BUFFER_POINTS - cur > 0) {
            lfs_spiflash_write(file, &g_scope_dma_points[PING][cur], (SCOPE_ADC_BUFFER_POINTS - cur) * sizeof(scope_adc_data));
        }
        if (cur > 0) {
            lfs_spiflash_write(file, &g_scope_dma_points[PING][0], cur * sizeof(scope_adc_data));
        }
    }
    lfs_spiflash_close(file);
    log_printf("save done\n");
}
HTTPD_CGI_PARAM_DEFINE("save", scope_proc_save_wave_data);

static void scope_proc_load_wave_data(char *value)
{
    lfs_file_t *file;
    int cur = (SCOPE_ADC_BUFFER_WORDS - dma_channel_hw_addr(g_scope_cfg.dma_chan_adc_data)->transfer_count) * 2;

    if (!value || strlen(value) == 0) {
        return;
    }
    pio_sm_set_enabled(SCOPE_ADC_PIO, SCOPE_ADC_TO_BUFFER_SM, false);
    file = lfs_spiflash_open(value, LFS_O_RDONLY, false);
    if (!file) {
        return;
    }
    lfs_spiflash_read(file, &g_scope_cfg, sizeof(g_scope_cfg));
    if (SCOPE_ADC_BUFFER_POINTS - cur > 0) {
        lfs_spiflash_read(file, &g_scope_dma_points[PING][cur], (SCOPE_ADC_BUFFER_POINTS - cur) * sizeof(scope_adc_data));
    }
    if (cur > 0) {
        lfs_spiflash_read(file, &g_scope_dma_points[PING][0], cur * sizeof(scope_adc_data));
    }
    lfs_spiflash_close(file);
    log_printf("load done\n");
}
HTTPD_CGI_PARAM_DEFINE("load", scope_proc_load_wave_data);

